package com.sams.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.sams.entity.Notice;
import com.sams.entity.Policy;
import com.sams.entity.School;
import com.sams.entity.User;
import com.sams.service.PolicyService;
import com.sams.util.PropertiesUtil;
import com.sams.util.ZipFileUtil;

@RequestMapping("/policy")
@Controller
public class PolicyController {
	
	@Autowired
	private PolicyService service;
	@RequestMapping("/list")
	public String list(Integer currentPage,String name,Model model) {
		if(currentPage==null) {
			currentPage=1;
		}
		// 以前存 list  和  page对象 ，现在存 分页框架的pageInfo
		// PageInfo 相当于  以前的Page 
		 
		PageInfo<Policy> pageInfo = service.list(currentPage,name);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("name", name);
		return "policy";
	}
	@ResponseBody
	@RequestMapping("/getList")
	public List<Policy> getList(){
		List<Policy> list = service.getList();
		return list;
	}
	@RequestMapping("/listFront")
	public String listFront(Integer currentPage,String name,Model model) {
		if(currentPage==null) {
			currentPage=1;
		}
		// 以前存 list  和  page对象 ，现在存 分页框架的pageInfo
		// PageInfo 相当于  以前的Page 
		 
		PageInfo<Policy> pageInfo = service.list(currentPage,name);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("name", name);
		return "detailpolicyList";
	}
	/**
	 * 添加
	 * @param file
	 * @param request
	 * @param model
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("/add")
	public String add(
			@RequestParam("name") String name,
			@RequestParam("content") String content,
			@RequestParam("publishdate") Date publishdate,
			@RequestParam("policyno") String policyno,
			@RequestParam("publishname") String publishname,
			@RequestParam("filepath") MultipartFile filepath,
			HttpServletRequest request,Model model) throws IllegalStateException, IOException {
		// 1.获取前端表单上传的文件，获取文件名getOriginalFilename()，判断是否是Excel文件
		/*String fileName = filepath.getOriginalFilename();
		System.out.println(fileName);*/
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		File newFile=null;
		try {
 

			File file = new File(PropertiesUtil.getProperty("imagePath") + File.separator + "policy");
			if (!file.exists()) {// 如果文件夹不存在
				file.mkdirs();// 创建文件夹
			}
			String policyfile = getFileName(filepath.getOriginalFilename());
			newFile = new File(file.getPath() + File.separator + policyfile);
			// 上传文件
			filepath.transferTo(newFile);

			// 添加policy
			Policy policy = new Policy();
			policy.setName(name);
			policy.setContent(content);
			policy.setFilepath("policy/" + policyfile);
			policy.setCreatedate(new Date());
			policy.setPolicyno(policyno);
			policy.setPublishdate(publishdate);
			policy.setPublishname(publishname);
			int count = service.add(policy);

			return "redirect:list";
		} catch (IOException e) {
			 //删除文件 
			if(newFile!=null) {
				newFile.delete();
			}
			e.printStackTrace();
			return "error";
		}
	}
	
	@RequestMapping("/delete")
	public String delete(Integer id) {
		Policy policy = service.findById(id);
		//先删除服务器上的文件 ，再删除业务数据   同时还删除浏览人的记录
		File file = new File(PropertiesUtil.getProperty("imagePath") + File.separator + policy.getFilepath());
		if(file!=null) {
			file.delete();
		}
		//删除
		service.delete(id);

		return "forward:/policy/list";
	}
	//新文件名字
	public String getFileName(String fileName) {
		String filePrefix=fileName.substring(0,fileName.lastIndexOf('.'));
        String fileSuffix=fileName.substring(fileName.lastIndexOf('.'), fileName.length());
       return filePrefix+(int)(Math.random()*9000+1000)+fileSuffix;
	}
	@RequestMapping("/downFile")
	public String downFile(Integer id, HttpServletRequest request, HttpServletResponse response) {
		//根据id 查询地址
		Policy policy = service.findById(id);
		  File file = new File(PropertiesUtil.getProperty("imagePath") + File.separator + policy.getFilepath());
		  ZipFileUtil.downloadFile(file, response, false);
		  return null;
	}
	@RequestMapping("/detailpolicy")
	public String detailpolicy(Integer id, HttpServletRequest request, HttpServletResponse response) {
		//根据id 查询地址
		Policy policy = service.findById(id);
		request.setAttribute("policy", policy);
		return "detailpolicy";
	}
	
	@InitBinder
	public void initBinder(ServletRequestDataBinder bin){
	         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	         CustomDateEditor cust = new CustomDateEditor(sdf,true);
	         bin.registerCustomEditor(Date.class,cust);
	}
}
